package test.io;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.ByteBuffer;

import com.google.code.bigyang.util.DumpUtil;
import com.google.code.bigyang.util.Dumpable;

public class MyBuffer implements Dumpable {

	private final ByteBuffer buf;
	
	public MyBuffer(ByteBuffer buf) {
		this.buf = buf;
	}
	
	public InputStream asInputStream() {
		
		return new MyInputStream();
	}
	
	public OutputStream asOutputStream() {
		return new MyOutputStream();
	}
	
	public String dump() {
		return DumpUtil.dump(buf);
	}

	public void dump(Appendable out, String indent) throws IOException {
		// TODO Auto-generated method stub
	}

	




	private class MyInputStream extends InputStream {
		@Override
		public int available() throws IOException {
			return buf.limit() - buf.position();
		}

		@Override
		public int read() throws IOException {
			if(buf.hasRemaining()) {
				return buf.get() & 0xFF;
			} else {
				return -1;
			}
		}

		@Override
		public int read(byte[] b) throws IOException {
			return read(b, 0, b.length);
		}

		@Override
		public int read(byte[] b, int off, int len) throws IOException {
			int remaining = buf.remaining();
			if(remaining > 0) {
				int readBytes = Math.min(remaining, len);
				buf.get(b, off, readBytes);
				return readBytes;
			}
			return -1;
		}

		@Override
		public long skip(long n) throws IOException {
			int skipBytes;
			if(n > Integer.MAX_VALUE) {
				skipBytes = buf.remaining();
			} else {
				skipBytes = Math.min(buf.remaining(), (int)n);
			}
			return skipBytes;
		}

		@Override
		public void close() throws IOException {
			
		}

		@Override
		public synchronized void mark(int readlimit) {
			buf.mark();
		}

		@Override
		public synchronized void reset() throws IOException {
			buf.reset();
		}

		@Override
		public boolean markSupported() {
			return true;
		}
		
	}
	
	
	
	private class MyOutputStream extends OutputStream {
		@Override
		public void write(int b) throws IOException {
			buf.put((byte)b);
		}

		@Override
		public void write(byte[] b) throws IOException {
			write(b, 0, b.length);
		}

		@Override
		public void write(byte[] b, int off, int len) throws IOException {
			buf.put(b, off, len);
		}

		@Override
		public void flush() throws IOException {
		}

		@Override
		public void close() throws IOException {
		}
		
	}
	
	
}
